﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Data.EntityClasses;
using NetDon.OA.Interface;
using NetDon.OA.Interface.CRM;
using NetDon.OA.Interface.Common;
using NetDon.OA.Interface.Configuration;
using NetDon.Utilities;
using NetDon.WebControls;

namespace NetDon.OA.Portal.Shunting
{
    [Navigation("干线流程", "调车信息编辑")]
    public partial class ShuntingInfoEdit : NavigationPageBase
    {
        protected Guid Id
        {
            set { ViewState["Id"] = value; }
            get
            {
                if (ViewState["Id"] != null)
                    return ViewState["Id"].ToString().ToGuid();
                return Guid.Empty;
            }
        }

        protected override IList<Guid> Ids
        {
            get
            {
                if (string.IsNullOrWhiteSpace(this.fieldIds.Value))
                    return new List<Guid>();
                return this.fieldIds.Value.Split(new char[] { ',' }).Select(id => id.ToGuid()).ToList();

            }
        }

        protected decimal? ShuntingCost
        {
            set { ViewState["ShuntingCost"] = value; }
            get
            {
                if (ViewState["ShuntingCost"] != null)
                    return Decimal.Parse(ViewState["ShuntingCost"].ToString());
                return null;
            }
        }


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);


        }
        void ClearInitialDropdown()
        {

            ddlPaymentMethod.Items.Clear();
            ddlShuntingPerson.Items.Clear();

        }
        protected void Page_Load(object sender, EventArgs e)
        {

            txtPlannedShippingDateCalendarExtender1.Format = SystemConfiguration.DateFormat;

            if (!IsPostBack)
            {
                CancelButton = btnCancel;
            }

        }

        private void LoadInitialView()
        {

            CurrentIndex = -1;
            LoadUserControl(Ids.Count > 0 ? Ids[++CurrentIndex] : Guid.Empty);
            SetButtonState(Ids.Count <= 0, true, false, Ids.Count == 1);
        }

        protected void rptVehicleInfo_ItemCreated(object sender, RepeaterItemEventArgs e)
        {


            if ((e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) &&
                e.Item.ItemType != ListItemType.SelectedItem) return;


            var objectDataSourceVechicleModel =
                e.Item.FindControl("ObjectDataSourceVechicleModel") as ObjectDataSource;

            objectDataSourceVechicleModel.Selecting += (ds, dsArgs) =>
                                                           {
                                                               dsArgs.InputParameters["areaId"] =
                                                                   CurrentApplicationContext.CompanyId.ToString();
                                                           };

            var ddlVechicleModel = e.Item.FindControl("ddlVechicleModel") as DropDownList;
            ddlVechicleModel.Attributes.Add("onchange", "setFocus(this,'{0}');".Formato(ddlVechicleModel.ClientID));

        }

        protected void rptVehicleInfo_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {


            if ((e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) &&
                e.Item.ItemType != ListItemType.SelectedItem) return;

            var vehicleData = e.Item.DataItem as IssuingOrderVehicleData;
            var formPanel = e.Item;

            var ddlVechicleModel = formPanel.FindControl("ddlVechicleModel") as DropDownList;

            ddlVechicleModel.InsertEmptyItem(ListEmptyType.Select);
            if (vehicleData.VechicleModel.HasValue)
                ddlVechicleModel.SelectedValue = vehicleData.VechicleModel.ToString();

            var txtDriverAppointedDateCalendarExtender1 =
                formPanel.FindControl("txtDriverAppointedDateCalendarExtender1") as AjaxControlToolkit.CalendarExtender;

            txtDriverAppointedDateCalendarExtender1.Format = SystemConfiguration.DateFormat;


            var txtDriverOnboardDateCalendarExtender2 =
               formPanel.FindControl("txtDriverOnboardDateCalendarExtender2") as AjaxControlToolkit.CalendarExtender;

            txtDriverOnboardDateCalendarExtender2.Format = SystemConfiguration.DateFormat;



            var txtDriverAppointedDate = formPanel.FindControl("txtDriverAppointedDate") as TextBox;

            var txtDriverAppointedDateHour = formPanel.FindControl("txtDriverAppointedDateHour") as TextBox;
            var txtDriverAppointedDateMinute = formPanel.FindControl("txtDriverAppointedDateMinute") as TextBox;
            var txtDriverOnboardDate = formPanel.FindControl("txtDriverOnboardDate") as TextBox;
            var txtDriverOnboardDateHour = formPanel.FindControl("txtDriverOnboardDateHour") as TextBox;
            var txtDriverOnboardDateMinute = formPanel.FindControl("txtDriverOnboardDateMinute") as TextBox;
            var txtDriverDelayedHours = formPanel.FindControl("txtDriverDelayedHours") as Label;

            AttachDriverDelayedHoursEvent(txtDriverAppointedDate, txtDriverAppointedDate, txtDriverOnboardDate, txtDriverAppointedDateHour, txtDriverAppointedDateMinute, txtDriverOnboardDateHour, txtDriverOnboardDateMinute, txtDriverDelayedHours);

            AttachDriverDelayedHoursEvent(txtDriverAppointedDateHour, txtDriverAppointedDate, txtDriverOnboardDate, txtDriverAppointedDateHour, txtDriverAppointedDateMinute, txtDriverOnboardDateHour, txtDriverOnboardDateMinute, txtDriverDelayedHours);

            AttachDriverDelayedHoursEvent(txtDriverAppointedDateMinute, txtDriverAppointedDate, txtDriverOnboardDate, txtDriverAppointedDateHour, txtDriverAppointedDateMinute, txtDriverOnboardDateHour, txtDriverOnboardDateMinute, txtDriverDelayedHours);

            AttachDriverDelayedHoursEvent(txtDriverOnboardDate, txtDriverAppointedDate, txtDriverOnboardDate, txtDriverAppointedDateHour, txtDriverAppointedDateMinute, txtDriverOnboardDateHour, txtDriverOnboardDateMinute, txtDriverDelayedHours);

            AttachDriverDelayedHoursEvent(txtDriverOnboardDateHour, txtDriverAppointedDate, txtDriverOnboardDate, txtDriverAppointedDateHour, txtDriverAppointedDateMinute, txtDriverOnboardDateHour, txtDriverOnboardDateMinute, txtDriverDelayedHours);

            AttachDriverDelayedHoursEvent(txtDriverOnboardDateMinute, txtDriverAppointedDate, txtDriverOnboardDate, txtDriverAppointedDateHour, txtDriverAppointedDateMinute, txtDriverOnboardDateHour, txtDriverOnboardDateMinute, txtDriverDelayedHours);



            if (vehicleData.DriverAppointedDate.HasValue)
            {
                txtDriverAppointedDateHour.Text = vehicleData.DriverAppointedDate.Value.ToString("HH");
                txtDriverAppointedDateMinute.Text = vehicleData.DriverAppointedDate.Value.ToString("mm");
            }

            if (vehicleData.DriverOnboardDate.HasValue)
            {
                txtDriverOnboardDateHour.Text = vehicleData.DriverOnboardDate.Value.ToString("HH");
                txtDriverOnboardDateMinute.Text = vehicleData.DriverOnboardDate.Value.ToString("mm");
            }
            if (string.IsNullOrWhiteSpace(txtDriverAppointedDate.Text))
            {
                txtDriverAppointedDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                txtDriverAppointedDateHour.Text = DateTime.Now.ToString("HH");
                txtDriverAppointedDateMinute.Text = DateTime.Now.ToString("mm");
            }

            if (string.IsNullOrWhiteSpace(txtDriverOnboardDate.Text))
            {
                txtDriverOnboardDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                txtDriverOnboardDateHour.Text = DateTime.Now.ToString("HH");
                txtDriverOnboardDateMinute.Text = DateTime.Now.ToString("mm");

            }
            var txtShuntingCost = e.Item.FindControl("txtShuntingCost") as TextBox;
            if (txtShuntingCost != null)
            {
                txtShuntingCost.Attributes.Add("onchange", "calculateUnitCosts(this);");

            }
            var txtWidth = e.Item.FindControl("txtWidth") as Label;
            var txtHeight = e.Item.FindControl("txtHeight") as Label;
            var txtLength = e.Item.FindControl("txtLength") as Label;

            LoadVehicleModelInfo(ddlVechicleModel, txtWidth, txtHeight, txtLength);

        }

        public void LoadUserControl(Guid id)
        {
            Id = id;


            var orderService = ServiceContainer.GetService<IIssuingOrderService>();
            var issuingOrderData = orderService.GetIssuingOrder(Id);

            ClearInitialDropdown();
            FormPanelIssuringOrderInfo.DataSource = issuingOrderData;
            FormPanelIssuringOrderInfo.DataBind();

            FormPanelBasicInfo.DataSource = issuingOrderData;
            FormPanelBasicInfo.DataBind();
            //LoadShuntingCost(issuingOrderData);


            hiddenActualEntruckingAmount.Value = issuingOrderData.ActualEntruckingAmount.ToString();

            if (issuingOrderData.ShuntingPerson.HasValue)
                ddlShuntingPerson.SelectedValue = issuingOrderData.ShuntingPerson.ToString();

            if (issuingOrderData.PaymentMethod.HasValue)
                ddlPaymentMethod.SelectedValue = issuingOrderData.PaymentMethod.ToString();



            if (string.IsNullOrWhiteSpace(txtPlannedShippingDate.Text))
                txtPlannedShippingDate.Text = DateTime.Now.ToString("yyyy-MM-dd");

            var issuingOrderVehicleData = orderService.GetIssuingOrderVehicleInfo(Id);
            this.rptVehicleInfo.DataSource = issuingOrderVehicleData;
            rptVehicleInfo.DataBind();

            OrderStatus = issuingOrderData.OrderStatus;
            ShuntingCost = issuingOrderData.ShuntingCost;
            FormPanelIssuringOrderInfo.Enabled = IsEditable();

            if(!IsManager())
            {
                if (ShuntingCost.HasValue && ShuntingCost.Value > 0)
                {
                    this.txtShuntingCost.Enabled = false;
                }
            }

        }

        //private void LoadShuntingCost(IssuingOrderData issuingOrderData)
        //{
        //    var service = ServiceContainer.GetService<IShuntingCostConfigService>();
        //    var shuntingCost =
        //        service.GetShuntingCostConfigDatasByCondition(new ShuntingCostConfigDataSearchCriteria()
        //                                                             {
        //                                                                 AreaId = CurrentApplicationContext.CompanyId,
        //                                                                 CheckoutType = (int)issuingOrderData.CheckoutType,
        //                                                                 DeliveryCity = issuingOrderData.DeliveryCity,
        //                                                                 RouteTypeId = issuingOrderData.RouteTypeId
        //                                                             });
        //    if (shuntingCost != null)
        //    {
        //        if (issuingOrderData.ShuntingCost.HasValue && issuingOrderData.ShuntingCost.Value > 0)
        //            return;
        //        if (shuntingCost.ShuntingCost.HasValue)
        //            this.txtShuntingCost.Text = shuntingCost.ShuntingCost.ToString();
        //        if (shuntingCost.UnitCost.HasValue)
        //            this.txtShuntingCost.Text = shuntingCost.UnitCost.ToString();
        //    }
        //}
        protected override bool IsEditable()
        {
            if (IsManager()) return true;
            return (OrderStatus == OrderStatus.Submitted || OrderStatus == OrderStatus.Shunted);
        }

        void SetButtonState(bool isAdd, bool isFirst, bool isLast, bool isSingleEdit)
        {
            SetButtonState(isAdd, isFirst, isLast, isSingleEdit, this.btnSave, btnCancel, btnPrevious, btnNext, btnSaveAndPrevious, btnSaveAndNext, panelBasic);

        }

        public bool SaveOrder()
        {
            DateTime plannedShippingDate = DateTime.MinValue;
            DateTime.TryParse(txtPlannedShippingDate.Text, out plannedShippingDate);
            ;
            IList<IssuingOrderVehicleData> orderVehicles = new List<IssuingOrderVehicleData>();
            if (!ExtractIssuingOrderVehicleData(out orderVehicles))
            {
                return false;
            }

            var service = ServiceContainer.GetService<IIssuingOrderService>();
            var order = service.GetIssuingOrder(Id);
            order.IssuingOrderDeliveryDataList = new List<IssuingOrderDeliveryData>();

            order.IssuingOrderVehicleDataList = orderVehicles;
            order.OrderStatus =(int)order.OrderStatus >(int)OrderStatus.Shunted ? order.OrderStatus :OrderStatus.Shunted;

            order.Id = Id != Guid.Empty ? Id : Guid.NewGuid();
            if (plannedShippingDate != DateTime.MinValue)
                order.PlannedShippingDate = plannedShippingDate;

            order.DelayedDays = SystemUtility.GetDelayedDays(plannedShippingDate, order.ActualShippingDate);

            order.ShuntingPerson = ddlShuntingPerson.SelectedValue.ToGuid();

            order.PaymentMethod = ddlPaymentMethod.SelectedValue.ToGuid();

            order.ShuntingCostExceptionComment = StringUtilities.Trim(txtShuntingCostExceptionsComment.Text);

            order.ShuntingCost = this.txtShuntingCost.Text.ToDecimal() ?? 0;
            order.GoodsUnloadingCost = 0;
            order.AreaId = (CurrentApplicationContext).CompanyId;
            order.LastUpdatedBy = CurrentApplicationContext.UserId;
            order.LastUpdatedDate = DateTime.Now;
            order.IsClientReturnVisit = chbIsClientReturnVisit.Checked;
            order.ClientTelephone = txtClientTelephone.Text.Trim();
            bool result = false;
            result = Id != Guid.Empty ? service.ModifyOrder(order) : service.AddOrder(order);
            if (result)
                Success("保存成功!");
            return result;


        }

        protected void btnReLoadIds_Click(object sender, EventArgs e)
        {
            LoadInitialView();
            btnReLoadIds.Enabled = false;
        }





        protected void btnSaveAndNext_Click(object sender, EventArgs e)
        {
            if (SaveOrder())
            {

                btnNext_Click(sender, e);

            }
        }
        protected void btnSaveAndPrevious_Click(object sender, EventArgs e)
        {
            if (SaveOrder())
            {

                btnPrevious_Click(sender, e);

            }
        }
        protected void btnNext_Click(object sender, EventArgs e)
        {

            if (HasNextView())
            {
                LoadNavigationView(Ids[++CurrentIndex]);
            }

            SetButtonState(false, IsFirstView, IsLastView, false);



        }
        protected void btnPrevious_Click(object sender, EventArgs e)
        {
            if (HasPreviousView())
            {
                LoadNavigationView(Ids[--CurrentIndex]);

            }
            SetButtonState(false, IsFirstView, IsLastView, false);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (SaveOrder())
            {
                CloseWindow(true);
            }

        }

        public void ddlVechicleModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            var ddl = sender as DropDownList;
            var repeater = ddl.Parent.Parent as Repeater;
            int n = ((RepeaterItem)ddl.Parent).ItemIndex;

            if (repeater != null)
            {
                var txtWidth = repeater.Items[n].FindControl("txtWidth") as Label;
                var txtHeight = repeater.Items[n].FindControl("txtHeight") as Label;
                var txtLength = repeater.Items[n].FindControl("txtLength") as Label;
                LoadVehicleModelInfo(ddl, txtWidth, txtHeight, txtLength);

            }

        }



        private bool ExtractIssuingOrderVehicleData(out IList<IssuingOrderVehicleData> orderVehicles)
        {
            orderVehicles = new List<IssuingOrderVehicleData>();
            foreach (RepeaterItem repeaterItem in this.rptVehicleInfo.Items)
            {
                if ((repeaterItem.ItemType != ListItemType.Item && repeaterItem.ItemType != ListItemType.AlternatingItem) &&
               repeaterItem.ItemType != ListItemType.SelectedItem) continue;

                var formPanel = repeaterItem;

                var txtDriverAppointedDate = formPanel.FindControl("txtDriverAppointedDate") as TextBox;

                var txtDriverAppointedDateHour = formPanel.FindControl("txtDriverAppointedDateHour") as TextBox;
                var txtDriverAppointedDateMinute = formPanel.FindControl("txtDriverAppointedDateMinute") as TextBox;
                var txtDriverOnboardDate = formPanel.FindControl("txtDriverOnboardDate") as TextBox;
                var txtDriverOnboardDateHour = formPanel.FindControl("txtDriverOnboardDateHour") as TextBox;
                var txtDriverOnboardDateMinute = formPanel.FindControl("txtDriverOnboardDateMinute") as TextBox;
                var txtDriverDelayedHours = formPanel.FindControl("txtDriverDelayedHours") as Label;



                DateTime driverAppointedDate = DateTime.MinValue, driverOnboardDate = DateTime.MinValue;


                if (!string.IsNullOrWhiteSpace(txtDriverAppointedDate.Text))
                {
                    if (!DateTime.TryParse(txtDriverAppointedDate.Text, out driverAppointedDate))
                    {
                        Alert("请输入合法的车辆预约时间。");
                        return false;
                    }
                }

                if (!string.IsNullOrWhiteSpace(txtDriverOnboardDate.Text))
                {
                    if (!DateTime.TryParse(txtDriverOnboardDate.Text, out driverOnboardDate))
                    {
                        Alert("请输入合法的车辆到厂时间。");
                        return false;
                    }
                }

                //if (driverAppointedDate > driverOnboardDate)
                //{
                //    Alert("车辆到厂时间应该大于等于预约时间。");
                //    return false;
                //}

                int driverOnboardHour = 0, driverOnboardMinute = 0;
                int driverAppointedHour = 0, driverAppointedMinute = 0;
                if (!string.IsNullOrWhiteSpace(txtDriverAppointedDateHour.Text) && !int.TryParse(txtDriverAppointedDateHour.Text, out driverAppointedHour))
                {
                    Alert("请输入正确的车辆预约小时数。");
                    return false;
                }

                if (!string.IsNullOrWhiteSpace(txtDriverOnboardDateHour.Text) && !int.TryParse(txtDriverOnboardDateHour.Text, out driverOnboardHour))
                {
                    Alert("请输入正确的车辆到厂小时数。");
                    return false;
                }


                if (!int.TryParse(txtDriverAppointedDateMinute.Text, out driverOnboardMinute))
                {
                    Alert("请输入正确的车辆预约分钟数。");
                    return false;
                }

                if (!int.TryParse(txtDriverOnboardDateMinute.Text, out driverAppointedMinute))
                {
                    Alert("请输入正确的车辆到厂分钟数。");
                    return false;
                }
                var orderVehicle = new IssuingOrderVehicleData();

                var hiddenIssuringOrderVehicleId = formPanel.FindControl("hiddenIssuringOrderVehicleId") as HiddenField;
                orderVehicle.Id = hiddenIssuringOrderVehicleId.Value.ToGuid();
                var txtCarSharingPrice = formPanel.FindControl("txtCarSharingPrice") as TextBox;
                orderVehicle.CarSharingPrice = txtCarSharingPrice.Text.ToDecimal();
                //var txtGoodsUnloadingPirce = formPanel.FindControl("txtGoodsUnloadingPirce") as TextBox;
                //orderVehicle.GoodsUnloadingPirce = txtGoodsUnloadingPirce.Text.ToDecimal();
                var ddlVechicleModel = formPanel.FindControl("ddlVechicleModel") as DropDownList;
                if (!string.IsNullOrWhiteSpace(ddlVechicleModel.SelectedValue))
                    orderVehicle.VechicleModel = ddlVechicleModel.SelectedValue.ToGuid();

                var txtVehicleNumber = formPanel.FindControl("txtVehicleNumber") as TextBox;
                orderVehicle.VehicleNumber = StringUtilities.Trim(txtVehicleNumber.Text);
                var txtDriverName = formPanel.FindControl("txtDriverName") as TextBox;
                orderVehicle.DriverName = StringUtilities.Trim(txtDriverName.Text);
                var txtDriverTelephone = formPanel.FindControl("txtDriverTelephone") as TextBox;
                orderVehicle.DriverTelephone = StringUtilities.Trim(txtDriverTelephone.Text);
                orderVehicle.DriverAppointedDate =
                    driverAppointedDate.AddHours(driverAppointedHour).AddMinutes(driverAppointedMinute);
                orderVehicle.DriverOnboardDate =
                   driverOnboardDate.AddHours(driverOnboardHour).AddMinutes(driverOnboardMinute);
                orderVehicle.DriverDelayedHours = SystemUtility.GetDelayedDays(orderVehicle.DriverAppointedDate, orderVehicle.DriverOnboardDate) * 24;
                var txtDriverDelayedReasons = formPanel.FindControl("txtDriverDelayedReasons") as TextBox;
                orderVehicle.AreaId = CurrentApplicationContext.CompanyId;
                orderVehicle.IssuingOrderId = Id;
                orderVehicle.DriverDelayedReasons = StringUtilities.Trim(txtDriverDelayedReasons.Text);
                orderVehicles.Add(orderVehicle);

            }

            return true;
        }


        private void LoadVehicleModelInfo(DropDownList ddlVechicleModel, Label txtWidth, Label txtHeight, Label txtLength)
        {
            if (!string.IsNullOrWhiteSpace(ddlVechicleModel.SelectedValue))
            {
                var vehicleMode = new VehicleModelEntity(ddlVechicleModel.SelectedValue.ToGuid());
                txtWidth.Text = Convert.ToDecimal(vehicleMode.Width).ToString("#,###.00");
                txtHeight.Text = Convert.ToDecimal(vehicleMode.Height).ToString("#,###.00");
                txtLength.Text = Convert.ToDecimal(vehicleMode.Length).ToString("#,###.00");
            }
        }

        void AttachDriverDelayedHoursEvent(TextBox textbox, TextBox txtDriverAppointedDate, TextBox txtDriverOnboardDate, TextBox txtDriverAppointedDateHour, TextBox txtDriverAppointedDateMinute, TextBox txtDriverOnboardDateHour, TextBox txtDriverOnboardDateMinute, Label txtDriverDelayedHours)
        {
            textbox.Attributes.Add("onchange", "calculateDriverDelayedDays(this,'{0}','{1}','{2}','{3}','{4}','{5}','{6}');".Formato(txtDriverAppointedDate.ClientID, txtDriverOnboardDate.ClientID, txtDriverAppointedDateHour.ClientID, txtDriverAppointedDateMinute.ClientID, txtDriverOnboardDateHour.ClientID, txtDriverOnboardDateMinute.ClientID, txtDriverDelayedHours.ClientID));
        }
        internal void LoadNavigationView(Guid id)
        {

            Id = id;

            LoadUserControl(id);

        }


    }
}